<?php
/**
 * Created by PhpStorm.
 * User: iceberg
 * Date: 2018-10-21
 * Time: 17:14
 */

namespace app\service;


use app\model\User;
use app\validate\UserValidate;
use think\facade\Request;

class SignService
{
    //登录检测
    public function check()
    {
        Request::isPost() || die('request not post!');
        //获取参数
        $param = Request::param();
        //统计登录次数
        session('login_num',session('login_num') + 1);
        if(session('login_num') >= 3){
            $error = $this->_validate($param, 'login_yzm');
            if(!is_null($error)){
                return ajax_return(103, $error);
            }
        }else{
            $error = $this->_validate($param, 'login');
            if(!is_null($error)){
                return ajax_return(100, $error);
            }
        }

        $user = User::where('username', $param['username'])->find();
        if(is_null($user)){
            return ajax_return(100, '用户名或者密码错误!');
        }
        if($user->password != md5($param['password'])){
            return ajax_return(100, '用户名或者密码错误!');
        }
        //登录次数归零
        session('login_num', 0);
        session('id', $user->id);
        session('username', $user->username);
        session('role', $user->role);

        return ajax_return(0, '登录成功！');
    }

    //注销
    public function logout()
    {
        //清除session
        session(null);
    }
    //验证器
    private function _validate($data, $scene='')
    {
        //验证
        $validate = new UserValidate();
        if(!$validate->scene($scene)->check($data))
        {
            return $validate->getError();
        }
    }
}